import os
from csv import *
from inventionmodels import *
from google.appengine.ext import webapp 

def loadCode():
    samples = reader(open('codesamples.csv').read().split('\r'));
    for sample in samples:
        sample = map(doFilter, sample)                    
        n, c, d, i1, i2 = sample
        CodeSample(name=n, codefile=c, image=os.path.splitext(c)[0] + '.jpg', \
                   desc=d, id1=int(i1), id2=int(i2)).put()
def loadWorkshop():
    workshops = reader(open('workshops2.csv').read().split('\r'));
    for w in workshops:
        if w:            
                w = map(doFilter, w)
                cId, i, a1, a2, aa, co, f, ld, ti, cr, h, s, rId, d, sd, tl, ph = w
                if ph:
                  ph = "mainimages/" + ph.split('/')[1] + ".jpg"
                else:
                  ph = "mainimages/01_11a.jpg"
                Workshop(codeId =cId.split(" "), insp = i, age1 = a1, age2 = a2, \
                           ageAvg = aa, cost = co, facilitators = f, longDesc = ld, \
                           time = ti, craft = cr, hardware = h, software = s, \
                           recordId = rId, date = d, shortDesc = sd, title = tl,
                           photoFolder = ph).put()
# -----------------------------------------------------
# split on '\n' not '\r'
# windows formatted csv files - sorry for the confusion 
# -----------------------------------------------------
def loadMaterial():
    materials = reader(open('materials.csv').read().split('\n'));
    for material in materials:
        material = map(doFilter, material)                    
        n, cst, wh, tps, im, typ = material
        Material(name=n, cost=cst, shere=wh, tips=tps, image='materials/'+im, type=typ).put()

def loadTheme():
    themes = reader(open('themes.csv').read().split('\n'));
    for theme in themes:
        theme = map(doFilter, theme)                    
        n, ids, im = theme
        Theme(name=n, image='themes/'+im, workshopIds=ids).put()
def loadRelational():
    #    for m in Material.all():
#        workshops = Workshop.gql("WHERE craft = :1", m.name)
#        for w in workshops:
#            MaterialRelationalEntry(material = m, workshop = w).put()

    for c in CodeSample.all():
        workshops = Workshop.gql("WHERE codeId = '" + "cd%03d"%(int(c.id1)) + "'")
        for w in workshops:
            RelationalEntry(codesample = c, workshop = w).put()

    for t in Theme.all():
        print t.name
        workshopIds = t.workshopIds.split(", ")
        for id in workshopIds:
            print id
            workshops = Workshop.gql("WHERE recordId = :1", id)
            for w in workshops:
                ThemeRelationalEntry(theme = t, workshop = w).put()


class LoadAll(webapp.RequestHandler):
  def get(self):
      loadCode()
      loadWorkshop()
      loadTheme()
      loadMaterial()
      loadRelational()
      self.redirect('/')

class LoadCode(webapp.RequestHandler):
  def get(self):
      loadCode()
      self.redirect('/')
class LoadWorkshop(webapp.RequestHandler):
  def get(self):
      loadWorkshop()
      self.redirect('/')    
class LoadTheme(webapp.RequestHandler):
  def get(self):
      loadTheme()
      self.redirect('/')
class LoadMaterial(webapp.RequestHandler):
  def get(self):
      loadMaterial()
      self.redirect('/')
class LoadRelational(webapp.RequestHandler):
  def get(self):
      loadRelational()
      self.redirect('/')

class ClearRelational(webapp.RequestHandler):
  def get(self):
    for w in RelationalEntry.all():
      w.delete()
    for w in ThemeRelationalEntry.all():
      w.delete()
    self.redirect('/')

class ClearWorkshop(webapp.RequestHandler):
  def get(self):
    for w in Workshop.all():
      w.delete()
    self.redirect('/')
    
class ClearCode(webapp.RequestHandler):
  def get(self):
    for cs in CodeSample.all():
      cs.delete()
    self.redirect('/')
class ClearMaterial(webapp.RequestHandler):
  def get(self):
    for m in Material.all():
      m.delete()
    self.redirect('/')
class ClearTheme(webapp.RequestHandler):
  def get(self):
    for t in Theme.all():
      t.delete()
    self.redirect('/')

class ClearAll(webapp.RequestHandler):
  def get(self):
    for w in Workshop.all():
      w.delete()
    for t in Theme.all():
      t.delete()
    for m in Material.all():
      m.delete()
    for cs in CodeSample.all():
      cs.delete()
    for w in RelationalEntry.all():
      w.delete()
    for w in ThemeRelationalEntry.all():
      w.delete()


def doFilter(item):
    return item.decode('ascii', 'replace').encode('ascii', 'replace').replace('\x0b', '').replace('\x1d', ' ')

def fromHex(str):
        if str and not isinstance(str, int):
                return int(str,16)
        else:
                return 0
